#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl

from django import template
from django.core.exceptions import FieldDoesNotExist
from django.utils.safestring import mark_safe
from django.utils.timezone import datetime, timedelta
register = template.Library()


@register.simple_tag
def render_app_name(admin_class):
    return admin_class.model._meta.verbose_name


# @register.simple_tag
# def get_query_sets(admin_class):
#     return admin_class.model.objects.all()


@register.simple_tag
def build_table_row(request, obj, admin_class):
    '''创建列'''
    row_ele = ""
    try:
        for k, column in enumerate(admin_class.list_display):
            field_obj = obj._meta.get_field(column)
            if field_obj.choices:
                column_data = getattr(obj, "get_%s_display" % (column,))()
            else:
                column_data = getattr(obj, column)
            if type(column_data).__name__ == "datetime":
                column_data = column_data.strftime("%Y-%m-%d %H:%M:%S")
            if k == 0:  # add a tag,可以跳转到修改页
                column_data = "<a href='{request_path}{obj_id}/change/'>{date}</a>".format(request_path=request.path,
                                                                                              obj_id=obj.id,
                                                                                              date=column_data)
            row_ele += "<td>%s</td>" % (column_data,)

    except FieldDoesNotExist as e:
            if hasattr(admin_class, column):
                column_func = getattr(admin_class,column)
                admin_class.instance = obj
                admin_class.request = request
                column_data = column_func()
                row_ele += "<td>%s</td>" % (column_data,)
    return mark_safe(row_ele)


@register.simple_tag
def build_paginators(query_sets, filter_conditions, previous_orderby ,search_key):
    '''返回整个分页元素'''
    page_btns = ''

    filters = ''

    for k, v in filter_conditions.items():
        filters += "%s=%s&" % (k, v)

    if len(query_sets.paginator.page_range) == 1:
        return ""

    added_dot_ele = False

    for page_num in query_sets.paginator.page_range:
        if page_num < 3 or page_num > query_sets.paginator.num_pages-2:  # 代表前后两页
            ele_class =""
            if page_num == query_sets.number:
                added_dot_ele = False
                ele_class = "active"
            page_btns += ''' <li class="%s"><a href="?page=%s&%s&o=%s&_q=%s">%s</a></li>''' % (ele_class, page_num, filters, previous_orderby, search_key, page_num )
        elif abs(query_sets.number - page_num) <= 1:
            ele_class = ""
            if page_num == query_sets.number:
                added_dot_ele = False
                ele_class = "active"
            page_btns += ''' <li class="%s"><a href="?page=%s&%s&o=%s&_q=%s">%s</a></li>''' % (ele_class, page_num, filters, previous_orderby, search_key, page_num )
        else:
            if added_dot_ele == False:
                page_btns += '<li><a>...</a></li>'
                added_dot_ele = True

    return mark_safe(page_btns)



# @register.simple_tag
# def render_page_ele(loop_counter, query_sets, filter_conditions):
#     filters = ''
#     for k, v in filter_conditions.items():
#         filters += "&%s=%s" % (k, v)
#     if len(query_sets.paginator.page_range) == 1:
#         return ""
#     if abs(query_sets.number-loop_counter) <= 2:
#         if loop_counter == query_sets.number:
#             ele = '''<li class="active"><a href="?page=%s%s">%s</a></li>''' % (loop_counter, filters, loop_counter)
#         else:
#             ele = '''<li class=""><a href="?page=%s%s">%s</a></li>''' % (loop_counter, filters, loop_counter)
#         return mark_safe(ele)


@register.simple_tag
def render_fileter_ele(filter_field, admin_class, filter_conditions):
    '''筛选选中'''
    select_ele = '''<select class="form-control" name='{filter_field}'><option value=''>-----</option>'''
    field_obj = admin_class.model._meta.get_field(filter_field)
    if field_obj.choices:
        selected =''
        for choice_item in field_obj.choices:
            if filter_conditions.get(filter_field) == str(choice_item[0]):
                selected = "selected"
            select_ele += '''<option value='%s' %s>%s</option>''' % (choice_item[0], selected, choice_item[1])
            selected = ''

    if type(field_obj).__name__ == "ForeignKey":
        selected = ''
        for choice_item in field_obj.get_choices()[1:]:
            if filter_conditions.get(filter_field) == str(choice_item[0]):
                selected = "selected"
            select_ele += '''<option value='%s' %s>%s</option>''' % (choice_item[0], selected, choice_item[1])
            selected = ''
    if type(field_obj).__name__ in ["DateTimeField", "DateField"]:
        today_ele = datetime.now().date()
        date_els = []
        yesterday_ele = today_ele - timedelta(days=1)
        last7days_ele = today_ele - timedelta(days=7)
        mtd_ele = today_ele.replace(day=1)  # 本月
        last30days_ele = today_ele -timedelta(days=30)
        last90days_ele = today_ele - timedelta(days=90)
        last180days_ele = today_ele - timedelta(days=180)
        last365days_ele = today_ele - timedelta(days=365)
        ytd_ele = today_ele.replace(month=1, day=1)  # 今年
        date_els.append(["今天", today_ele])
        date_els.append(["昨天", yesterday_ele])
        date_els.append(["近7天", last7days_ele])
        date_els.append(["近一个月", last30days_ele])
        date_els.append(["近三个月", last90days_ele])
        date_els.append(["近半年", last180days_ele])
        date_els.append(["近一年", last365days_ele])
        date_els.append(["本月", mtd_ele])
        date_els.append(["本年", ytd_ele])
        selected = ''
        for item in date_els:
            if filter_conditions.get(filter_field+"__gte") == str(item[1]):
                selected = "selected"
            select_ele += '''<option value='%s' %s>%s</option>''' % (item[1], selected, item[0])
            selected = ''
        filter_field_name = "%s__gte" % filter_field
    else:
        filter_field_name = filter_field
    select_ele += "</select>"
    select_ele = select_ele.format(filter_field=filter_field_name)
    return mark_safe(select_ele)


@register.simple_tag
def filters_cn(filter_conditions, previous_orderby, search_key):
    '''上一页下一页的url拼接'''
    filters = ''
    for k, v in filter_conditions.items():
        filters += "%s=%s" % (k, v)
    filters += "&o=%s" % (previous_orderby)
    filters += "&_q=%s" % (search_key)
    return filters


@register.simple_tag
def build_table_header_column(column, orderby_key, filter_conditions,admin_class):
    '''排序'''
    filters = ''
    for k, v in filter_conditions.items():
        filters += "&%s=%s" % (k, v)
    ele = '''<th><a href="?{filters}&o={orderby_key}">{column}</a>
    {sort_icon}
    </th>'''
    if orderby_key:
        if orderby_key.startswith("-"):
            sort_icon = '''<span class="glyphicon glyphicon-menu-up"  style="color: #d9edf7" aria-hidden="true" ></span>'''
        else:
            sort_icon = '''<span class="glyphicon glyphicon-menu-down" style="color: #d9edf7" aria-hidden="true"></span>'''
        if orderby_key.strip("-") == column:
            orderby_key = orderby_key

        else:
            orderby_key = column
            sort_icon = ''
    else:
        orderby_key = column
        sort_icon = ''
    try:
        column_verbose_name = admin_class.model._meta.get_field(column).verbose_name.upper()
    except FieldDoesNotExist as e:
        column_verbose_name = getattr(admin_class, column).display_name
        ele = '''<th><a href="javascript:void(0)">{column}</a></th>'''
    return mark_safe(ele.format(orderby_key=orderby_key, column=column_verbose_name, sort_icon=sort_icon, filters=filters))


@register.simple_tag
def get_model_name(admin_class):
    '''获得表名'''
    return admin_class.model._meta.verbose_name


@register.simple_tag
def get_m2m_obj_list(admin_class, field, form_obj):
    '''返回m2m所有待选数据'''
    field_obj = getattr(admin_class.model, field.name)
    all_obj_list = field_obj.rel.to.objects.all()  # 查询到所有待选数据
    if form_obj.instance.id:
        obj_instance_field = getattr(form_obj.instance, field.name)  # 查询到已选中的数据

        selected_obj_list = obj_instance_field.all()
    else:  # 代表新增数据
        return all_obj_list

    standby_obj_list = []

    for obj in all_obj_list:
        if obj not in selected_obj_list:
            standby_obj_list.append(obj)
    return standby_obj_list


@register.simple_tag
def get_m2m_selected_obj_list(form_obj, field):
    '''返回已选择的m2m数据'''
    if form_obj.instance.id:
        field_obj = getattr(form_obj.instance, field.name)
        return field_obj.all()


def recursive_related_objs_lookup(objs):
    # model_name = objs[0]._meta.model_name
    ul_ele = "<ul>"
    for obj in objs:
        # print("ddd-----obj",obj)
        li_ele = '''<li>%s: %s </li>''' %(obj._meta.verbose_name, obj.__str__().strip("<>"))
        ul_ele += li_ele

        sub_ul_ele = "<ul>"
        for m2m_field in obj._meta.local_many_to_many:  # 把所有跟这个对象直接关联的m2m字段取出来了

            m2m_field_obj = getattr(obj, m2m_field.name)  # getattr(customer, 'tag')

            for o in m2m_field_obj.select_related():
                li_ele = '''<li>%s: %s </li>''' % (m2m_field.verbose_name, o.__str__().strip("<>"))
                sub_ul_ele += li_ele
            sub_ul_ele += "</ul>"
            ul_ele += sub_ul_ele

        for related_obj in obj._meta.related_objects:
            if 'ManyToOneRel' not in related_obj.__repr__():
                if hasattr(obj, related_obj.get_accessor_name()):  # hassattr(customer, 'enrollment_set')
                    accessor_obj = getattr(obj, related_obj.get_accessor_name())
                    #  上面accessor_obj 相当于customer.enrollment_set
                    if hasattr(accessor_obj, 'select_related'):  # select_related() == all()
                        target_objs = accessor_obj.select_related()
                        #  target_objs 相当于 customer.enrollment_set.all()
                        sub_ul_ele = "<ul>"
                        for o in target_objs:
                            li_ele = '''<li>%s: %s </li>''' % (o._meta.verbose_name, o.__str__().strip("<>"))
                            sub_ul_ele += li_ele

                        sub_ul_ele += "</ul>"
                        ul_ele += sub_ul_ele

            elif hasattr(obj, related_obj.get_accessor_name()):  # hassattr(customer, 'enrollment_set')
                accessor_obj = getattr(obj, related_obj.get_accessor_name())
                #  上面accessor_obj 相当于customer.enrollment_set
                if hasattr(accessor_obj, 'select_related'):  # select_related() == all()
                    target_objs = accessor_obj.select_related()
                    #  target_objs 相当于 customer.enrollment_set.all()
                else:
                    #  one to one
                    target_objs = accessor_obj

                if len(target_objs) > 0:
                    nodes = recursive_related_objs_lookup(target_objs)
                    ul_ele += nodes
    ul_ele +="</ul>"
    return ul_ele

@register.simple_tag
def display_obj_related(objs):
    # objs = [objs, ]
    # print("tuype-------",type(objs))
    if objs:
        # print("objs-------",objs)
        # model_class = objs[0]._meta.model
        # model_name = objs[0]._meta.model_name
        return mark_safe(recursive_related_objs_lookup(objs,))


@register.simple_tag
def get_action_name(admin_class, action):
    action_func = getattr(admin_class, action)
    # return  action_func.display_name if hasattr(action_func, 'display_name') else action
    if hasattr(action_func, 'display_name'):
        return action_func.display_name
    else:
        return action
